{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8edb5930",
   "metadata": {},
   "source": [
    "# 循环\n",
    "\n",
    "循环的作用在于将一段代码重复执行多次。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd1c390b",
   "metadata": {},
   "source": [
    "## while 循环\n",
    "\n",
    "```python\n",
    "while <condition>:\n",
    "    <statesments>\n",
    "```\n",
    "\n",
    "Python会循环执行<statesments>，直到<condition>不满足为止。\n",
    "\n",
    "例如，计算数字0到1000000的和："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6975f14a",
   "metadata": {},
   "outputs": [],
   "source": [
    "i = 0\n",
    "total = 0\n",
    "while i < 1000000:\n",
    "    total += i\n",
    "    i += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "da7ac78c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "499999500000"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "total"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "704661bb",
   "metadata": {},
   "source": [
    "## for 循环\n",
    "```python\n",
    "for <variable> in <sequence>:\n",
    "    <indented block of code>\n",
    "```\n",
    "\n",
    "for 循环会遍历完<sequence>中所有元素为止\n",
    "\n",
    "上一个例子可以改写成如下形式："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c2e3019c",
   "metadata": {},
   "outputs": [],
   "source": [
    "total = 0\n",
    "for i in range(100000):\n",
    "    total += i"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b6fc9368",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4999950000"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "total"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "990f0904",
   "metadata": {},
   "source": [
    "## continue 语句\n",
    "\n",
    "遇到 continue 的时候，程序会返回到循环的最开始重新执行。\n",
    "\n",
    "例如在循环中忽略一些特定的值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "6e72b496",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6 3.0\n",
      "4 2.0\n",
      "2 1.0\n"
     ]
    }
   ],
   "source": [
    "values = [7, 6, 4, 7, 19, 2, 1]\n",
    "for i in values:\n",
    "    if i % 2 != 0:\n",
    "        # 忽略奇数\n",
    "        continue\n",
    "    print(i, i / 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e431d73",
   "metadata": {},
   "source": [
    "## break 语句\n",
    "遇到 break 的时候，程序会跳出循环，不管循环条件是不是满足："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0331bfe1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "start\n",
      "process\n",
      "process\n",
      "process\n"
     ]
    }
   ],
   "source": [
    "command_list = ['start', \n",
    "                'process', \n",
    "                'process',\n",
    "                'process', \n",
    "                'stop', \n",
    "                'start', \n",
    "                'process', \n",
    "                'stop']\n",
    "for command in command_list:\n",
    "    if command == 'stop':\n",
    "        break\n",
    "    print(command)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3f2c6d98",
   "metadata": {},
   "source": [
    "在遇到第一个 'stop' 之后，程序跳出循环。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9f5afc5",
   "metadata": {},
   "source": [
    "## else语句\n",
    "与 if 一样， while 和 for 循环后面也可以跟着 else 语句，不过要和break一起连用。\n",
    "\n",
    "当循环正常结束时，循环条件不满足， else 被执行；\n",
    "当循环被 break 结束时，循环条件仍然满足， else 不执行。\n",
    "不执行："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "52d4f118",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found: 7\n"
     ]
    }
   ],
   "source": [
    "values = [7, 6, 4, 7, 19, 2, 1]\n",
    "for x in values:\n",
    "    if x <= 10:\n",
    "        print('Found:', x)\n",
    "        break\n",
    "else:\n",
    "    print('All values greater than 10')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6b8c7904",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "All values greater than 10\n"
     ]
    }
   ],
   "source": [
    "values = [11, 12, 13, 100]\n",
    "for x in values:\n",
    "    if x <= 10:\n",
    "        print('Found:', x)\n",
    "        break\n",
    "else:\n",
    "    print('All values greater than 10')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa71eb93",
   "metadata": {},
   "source": [
    "## 列表推导式\n",
    "\n",
    "循环可以用来生成列表："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "dfa70d35",
   "metadata": {},
   "outputs": [],
   "source": [
    "values = [10, 21, 4, 7, 12]\n",
    "squares = []\n",
    "for x in values:\n",
    "    squares.append(x**2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "1249bae7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[100, 441, 16, 49, 144]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "squares"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79fdb227",
   "metadata": {},
   "source": [
    "列表推导式可以使用更简单的方法来创建这个列表："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "0583fffd",
   "metadata": {},
   "outputs": [],
   "source": [
    "squares = [x**2 for x in values]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68943c8f",
   "metadata": {},
   "source": [
    "还可以在列表推导式中加入条件进行筛选："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "2684b4ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "squares = [x**2 for x in values if x <= 10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "b0677d75",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[100, 16, 49]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "squares"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "589700d3",
   "metadata": {},
   "source": [
    "也可以使用推导式生成集合和字典："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "1fe3025b",
   "metadata": {},
   "outputs": [],
   "source": [
    "square_set = {x**2 for x in values if x <= 10}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "f0839739",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{16, 49, 100}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "square_set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "465545e4",
   "metadata": {},
   "outputs": [],
   "source": [
    "square_dict = {x: x**2 for x in values if x <= 10}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "1ed1aaed",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{10: 100, 4: 16, 7: 49}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "square_dict"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31645abd",
   "metadata": {},
   "source": [
    "计算上面例子中生成的列表中所有元素的和："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "37ee4ce5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "165"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum([x**2 for x in values if x <= 10])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "738a63fe",
   "metadata": {},
   "source": [
    "括号可以省略："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "e6f1a520",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "165"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum(x**2 for x in values if x <= 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a89c9c62",
   "metadata": {},
   "source": [
    "第二种写法会减少一次列表的生成，速度会更快一些。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1117cd3f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
